package exam.note.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import exam.aopLogger.Log;
import exam.note.domain.NoteType;
import exam.note.mapper.NoteTypeMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/4 20:52
 * @since JDK 1.8
 */
@RestController
@Api(tags = {"笔记类型模块"})
@RequestMapping("notetype")
public class NoteTypeController {

    @Autowired
    private NoteTypeMapper noteTypeMapper;

    private final transient ReentrantLock lock = new ReentrantLock();

    @ApiOperation("笔记类型添加模块")
    @GetMapping("add")
    @Log("笔记类型添加模块")
    public JSONObject addNoteTypeController(@ApiParam("类型名称")@RequestParam("type")String type){
        JSONObject jsonObject=new JSONObject();
        if(StringUtils.isEmpty(type)){
            jsonObject.put("code",1);
            jsonObject.put("msg","error");
            return jsonObject;
        }
        try {
            lock.lock();
            NoteType noteType=new NoteType();
            noteType.setTypeName(type);
            noteTypeMapper.insert(noteType);
        }finally {
            lock.unlock();
        }
        jsonObject.put("code",0);
        jsonObject.put("msg","success");
        return jsonObject;
    }


    @GetMapping()
    @ApiModelProperty("类型列表")
    @Log("类型列表")
    public JSONObject typeListController(){
        JSONObject jsonObject=new JSONObject();
        List<NoteType> noteTypes=noteTypeMapper.selectList(new LambdaQueryWrapper<>());
        JSONArray jsonArray=new JSONArray();
        noteTypes.stream().forEach(e->{
            JSONObject jsonObject1=(JSONObject)jsonObject.clone();
            jsonObject1.put("key",e.getId());
            jsonObject1.put("value",e.getTypeName());
            jsonArray.add(jsonObject1);
        });
        jsonObject.put("code",0);
        jsonObject.put("msg","success");
        jsonObject.put("data",jsonArray);
        return jsonObject;

    }
}
